package com.anlu.concurrent.ch2.forkjoin.test;

import java.sql.Timestamp;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveAction;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * Description:TODO 详细描述
 * <p>
 * Copyright: 天津联想协同科技有限公司
 * <p>
 *
 * @author anlu
 * @date 2021/9/6 17:42
 */
public class RaskDemo extends RecursiveAction {

    /**
     * 每个小任务 只能打印20个数
     */
    private static  final int MAX = 20;

    private  int start;
    private int end;

    public RaskDemo(int start, int end) {
        this.start = start;
        this.end = end;
    }

    @Override
    protected void compute() {
        if((end-start)<MAX){
            for (int i = start;i<end;i++){
                System.out.println(Thread.currentThread().getName()+" i的值:"+i);
            }
        }else{
            //将大任务分解为两个小任务
            int middle = (start+end)/2;
            System.out.println("middle="+middle);
            RaskDemo left = new RaskDemo(start,middle);
            RaskDemo right = new RaskDemo(middle,end);
            left.fork();
            right.fork();
        }
    }

    public static void main(String[] args) throws Exception{
        ForkJoinPool pool = new ForkJoinPool();
        //提交可分解的任务
        pool.submit(new RaskDemo(0,1000));
        pool.awaitTermination(2, TimeUnit.SECONDS);
        //关闭线程池
        pool.shutdown();
    }
}
